class WeblogsController < ApplicationController
  before_filter :login_required, :only => [ :new, :create, :edit, :update, :destroy ]

  # GET /weblogs
  # GET /weblogs.xml
  def index
    @weblogs = Weblog.find(:all)

    respond_to do |format|
      format.html # index.rhtml
      format.xml  { render :xml => @weblogs.to_xml }
    end
  end

  # GET /weblogs/1
  # GET /weblogs/1.xml
  def show
    @weblog = Weblog.find params[:id]
    @entry_pages, @entries = paginate :entry, :conditions => [ 'weblog_id = ?', @weblog.id ], :order => 'id DESC', :joins => 'e join holders h on holder_id = h.id', :select => 'e.*'

    respond_to do |format|
      format.html { render :layout => 'layouts/front' }
      format.xml  { render :xml => @weblog.to_xml }
    end
  end

  # GET /weblogs/new
  def new
    @weblog = Weblog.new
  end

  # GET /weblogs/1;edit
  def edit
    @weblog = Weblog.find params[:id]
  end

  # POST /weblogs
  # POST /weblogs.xml
  def create
    @weblog = Weblog.new params[:weblog] do |w|
      w.categories << Category.new(:name => 'Uncategorized', :description => 'Uncategorized')
      w.links      << Favourite.new(:name => 'Favourails', :url => 'http://www.favourails.org/', :description => 'Favourails')
    end

    respond_to do |format|
      if current_user.weblogs << @weblog
        format.html { redirect_to weblog_url(@weblog) }
        format.xml  { head :created, :location => weblog_url(@weblog) }
      else
        format.html { render :action => :new }
        format.xml  { render :xml => @weblog.errors.to_xml }
      end
    end
  end

  # PUT /weblogs/1
  # PUT /weblogs/1.xml
  def update
    @weblog = Weblog.find(params[:id])

    respond_to do |format|
      if @weblog.update_attributes(params[:weblog])
        flash[:notice] = 'Weblog was successfully updated.'
        format.html { redirect_to weblog_url(@weblog) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @weblog.errors.to_xml }
      end
    end
  end

  # DELETE /weblogs/1
  # DELETE /weblogs/1.xml
  def destroy
    @weblog = Weblog.find(params[:id])
    @weblog.destroy

    respond_to do |format|
      format.html { redirect_to weblogs_url }
      format.xml  { head :ok }
    end
  end
end
